from django.db.models import Q
from rest_framework import serializers
from frame_server.serializers import BaseSerializer as BSerializer
from .models import Menu

class BaseSerializer(BSerializer):
    id = serializers.CharField()
    parentId = serializers.CharField(source="parentId.pk", required=False, allow_null=True)
    parentName = serializers.CharField(source="parentId.name", required=False, allow_null=True)
    children = serializers.SerializerMethodField()
    hasChildren = serializers.SerializerMethodField()
    categoryName = serializers.SerializerMethodField()

    class Meta:
        model = Menu

    def get_hasChildren(self,obj):
        return obj.menu_set.exists()
    
    def get_children(self, obj):
        # 动态获取当前序列化器类
        serializer_class = self.__class__
        menuIds = self.context.get('menuIds')
        q = Q(category=1)
        if menuIds and len(menuIds):
            q &= Q(id__in=menuIds)
        objs = obj.menu_set
        if objs.filter(q).exists():
            return serializer_class(objs.filter(q), many=True, context=self.context).data
        return []

    def get_categoryName(self,obj):
        return obj.categoryName
    
# 路由菜单序列化
class RoutesSerializer(BaseSerializer):
    class Meta(BaseSerializer.Meta):
        fields = '__all__'
        
# 菜单管理-菜单详情数据序列化
class DetailSerializer(BaseSerializer):
    class Meta(BaseSerializer.Meta):
        fields = '__all__'

# 菜单管理-菜单表格数据序列化
class MenuLazyListSerializer(BaseSerializer):
    class Meta(BaseSerializer.Meta):
        fields = '__all__'

# 菜单管理-新增弹窗中上级菜单下拉列表序列化
class MenuTreeSerializer(BaseSerializer):
    class Meta(BaseSerializer.Meta):
        fields = '__all__'

# 角色管理-菜单权限配置树结构序列化
class GrantTreeSerializer(BaseSerializer):
    hasChildren = serializers.SerializerMethodField()

    def get_hasChildren(self,obj):
        return obj.menu_set.filter(category=1).exists()
    
    class Meta(BaseSerializer.Meta):
        fields = '__all__'